<template>
  <el-row justify="space-between">
    <span></span>
    <el-button v-if="checkPermission(Permissions.company,Action.add)" type="primary"
               @click="addCompanyDialogVisible = true">添加公司
    </el-button>
  </el-row>
  <el-divider/>
  <el-table :data="companies" stripe border>
    <el-table-column label="序号" prop="company_id"/>
    <el-table-column label="公司名字" prop="company_name"/>
    <el-table-column label="操作">
      <template #default="scope" v-if="checkPermission(Permissions.company, Action.delete)">
        <el-popconfirm
            class="box-item"
            :title="'确定删除' + scope.row.company_name + '吗？'"
            placement="top-start"
            @confirm="deleteCompanyFn(scope.row.company_id)">
          <template #reference>
            <el-button size="small" type="danger" :disabled="deleteLoading">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <add-company-dialog v-model="addCompanyDialogVisible" @success="refetch"/>
</template>

<script setup lang="ts">
import {useMutation, useQuery} from "@pinia/colada";
import {deleteCompany, getCompanies} from "../../api/company.ts";
import {ElMessage} from "element-plus"
import AddCompanyDialog from "./components/AddCompanyDialog.vue";
import {ref} from "vue";
import {useUserStore} from "../../store/userStore.ts";
import {Action, Permissions} from "../../types/permissions.ts";


const addCompanyDialogVisible = ref(false)

let {checkPermission} = useUserStore();

let {data: companies, refetch} = useQuery({
  key: ["company"],
  query: async () => getCompanies,
});

let {mutate: deleteCompanyFn, isLoading: deleteLoading} = useMutation({
  mutation: (companyId: number) => deleteCompany(companyId),
  onSuccess: () => {
    refetch()
    ElMessage.success("删除成功")
  },
  onError: () => {
    ElMessage.error("删除失败")
  }
});
</script>
<style scoped>

</style>